
const { cloudApiClient, mergeAgent, logger } = require('../utils');
const TenantService = require('../service/tenant');
const TenantSignRecordService = require('../service/tenantSignRecordService');
const ContractService = require('../service/contract');
const SendService = require('../service/sendRecordService');
const WorkerService = require('../service/worker');
// const UserService = require('../service/user');

const tenantService = new TenantService();
const tenantSignRecordService = new TenantSignRecordService();
const contractService = new ContractService();
const sendService = new SendService();
const workerService = new WorkerService();
// const userService = new UserService();

const getAgent = async (req) => {
  const { userInfo } = req;
  const targetUser = userInfo;
  if (!targetUser) {
    console.error('targetUser: not found');
    return false;
  }
  return {
    ...mergeAgent({
      ProxyOrganizationOpenId: targetUser.organizationOpenId,
      OpenId: targetUser.openId,
      ProxyAppId: targetUser.proxyAppId,
    }),
    OrganizationName: targetUser.organizationName,
    UserId: targetUser.userId,
    UserName: targetUser.userName,
  };
};

module.exports = (app) => {
  // 获取企业列表
  app.post(`${process.env.VUE_APP_BASE_API}/tenant/list`, async (req, res) => {
    const { userInfo, body } = req;
    const targetUser = userInfo;
    const { limit = 10, offset = 0, status } = body;
    if (targetUser) {
      const where = { organizationId: targetUser.organizationId };
      if (status === 'UNDISTURBED') {
        // 未发起
        where.latestFlowStatus = 'UNDISTURBED';
      } else if (status === 'INIT') {
        // 待签署
        where.latestFlowStatus = 'INIT';
      } else if (status === 'ALL') {
        // 已签署
        where.latestFlowStatus = 'ALL';
      }
      try {
        const list = await tenantService.search({
          where,
          offset,
          limit,
        });

        const totalCount = await tenantService.searchCount(where);

        return res.json({
          code: 20000,
          data: { tenants: list.map(item => {
            if (item.enterpriseOperator) {
              item.enterpriseOperator = JSON.parse(item.enterpriseOperator);
              item.createdOn = new Date(item.createdOn).getTime();
              item.contractEndDate = new Date(item.contractEndDate).getTime();
            }
            return item;
          }), totalCount },
        });
      } catch (error) {
        console.error(error);
        return res.json({
          code: 500,
          message: '用工单位列表数据查询失败',
        });
      }
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });

  // 新增企业
  app.post(`${process.env.VUE_APP_BASE_API}/tenant/create`, async (req, res) => {
    const { userInfo, body } = req;
    const targetUser = userInfo;
    if (targetUser) {
      const filterData = await tenantService.filter({ name: body.name, organizationId: userInfo.organizationId });
      if (filterData?.id) {
        return res.json({
          code: 50204,
          message: '该企业名称已存在，请重新填写',
        });
      }
      const newTenant = await tenantService.create({ ...body, organizationId: userInfo.organizationId });
      if (newTenant) {
        return res.json({
          code: 20000,
          data: newTenant,
          message: '新增企业成功',
        });
      }
      return res.json({
        code: 50204,
        message: '新增企业失败',
      });
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });

  // 修改企业
  app.post(`${process.env.VUE_APP_BASE_API}/tenant/update`, async (req, res) => {
    const { userInfo, body } = req;
    const targetUser = userInfo;
    if (targetUser) {
      const existRepeatNameTenants = await tenantService.filter({ organizationId: targetUser.organizationId, name: body.name });
      if (existRepeatNameTenants.length > 0 && existRepeatNameTenants.some(t => t.id !== body.id)) {
        return res.json({
          code: 50204,
          message: '该企业名称已存在，请重新填写',
        });
      }

      const status = await tenantService.update(body.id, {
        ...body,
        enterpriseOperator: JSON.stringify(body.enterpriseOperator),
      });
      if (status) {
        return res.json({
          code: 20000,
          data: { id: body.id },
          message: '修改用工企业信息成功',
        });
      }
      return res.json({
        code: 500,
        message: '修改用工企业信息失败',
      });
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });

  // 删除企业
  app.post(`${process.env.VUE_APP_BASE_API}/tenant/deleteById`, async (req, res) => {
    const { userInfo, body } = req;
    const targetUser = userInfo;
    if (targetUser) {
      const status = await tenantService.delete(body.id);
      if (status) {
        // 记录表更新
        // const deleteRes = await tenantSignRecordService.filter({
        //   tenantId: body.id,
        // });
        // if (deleteRes?.id) {
        //   const deleteStatus = await tenantSignRecordService.delete({
        //     id: deleteRes?.id,
        //   });
        //   const tenantSendRecords = await sendService.filter({ tenantId: body.id });// 用工单位派遣记录
        //   const tenantSignRecords = await tenantSignRecordService.filter({ tenantId: body.id });// 用工单位签署记录
        //   await Promise.all(tenantSendRecords.map(item => sendService.delete(item.id)));// 删除派遣记录
        //   for (const item of tenantSignRecords) {
        //     await contractService.delete(item.contractId);// 删除用工单位合同
        //     await tenantSignRecordService.delete(item.id);// 删除用工单位合同签署记录
        //   }


        //   console.log('allRecord====', deleteRes, deleteStatus);
        // await sendService.deleteByWhere({ tenantId: body.id });// 用工单位派遣记录
        // await tenantSignRecordService.deleteByWhere({ tenantId: body.id });// 用工单位签署记录
        return res.json({
          code: 20000,
          data: { id: body.id },
          message: '删除成功',
        });
      }
      return res.json({
        code: 500,
        message: '删除失败',
      });
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });

  // 终止合同
  app.post(`${process.env.VUE_APP_BASE_API}/tenant/stopContract`, async (req, res) => {
    const { userInfo, body } = req;
    const targetUser = userInfo;
    if (targetUser) {
      // 用工企业表更新状态
      const status = await tenantService.update(body.id, {
        id: body.id,
        latestFlowStatus: 'UNDISTURBED',
      });
      // 记录表更新状态
      await tenantSignRecordService.update(body.id, {
        tenantStatus: 'UNDISTURBED',
      });

      if (status) {
        return res.json({
          code: 20000,
          data: { id: body.id },
          message: '终止合同成功',
        });
      }
      return res.json({
        code: 500,
        message: '终止合同失败',
      });
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });

  // 模板批量创建签署流程
  app.post(`${process.env.VUE_APP_BASE_API}/tenant/createFlowsByTemplates`, async (req, res) => {
    const { body, userInfo } = req;
    const { UserName, UserId, ...agent } = await getAgent(req);
    body.flowInfos?.FlowApprovers.forEach((item) => {
      if (!item?.NotChannelOrganization) {
        item.OrganizationOpenId = userInfo.organizationOpenId;
        item.OpenId = userInfo.openId;
      }
    });
    const { flowInfos, tenantId, needPreview = false, previewType = 1 } = body;
    console.log('createFlowsByTemplates==== body====', body, agent);
    if (agent) {
      const params = {
        Agent: agent,
        Version: '2021-05-26',
        FlowInfos: [flowInfos],
        NeedPreview: needPreview,
        PreviewType: previewType || 1,
      };
      console.log('tenant createFlowsByTemplates params=====', params);

      try {
        const flowRes = await cloudApiClient.CreateFlowsByTemplates(params);

        if (flowRes.ErrorMessages && flowRes.ErrorMessages.length && flowRes.ErrorMessages[0]) {
          return res.json({
            code: 50000,
            message: flowRes.ErrorMessages.join(','),
          });
        }

        // 预览模式下不存储数据
        if (needPreview) {
          return res.json({ code: 20000, data: flowRes });
        }

        //   if (flowRes?.FlowIds && flowRes?.FlowIds?.length > 0) {
        //     const tempFlowid = flowRes?.FlowIds?.[0];
        //     const startDate = flowInfos?.FormFields.find(f => f.ComponentName === 'starttime')?.ComponentValue;
        //     const endDate = flowInfos?.FormFields.find(f => f.ComponentName === 'endtime')?.ComponentValue;
        //     const monthlyPay = flowInfos?.FormFields.find(f => f.ComponentName === 'monthlypay')?.ComponentValue;
        //     // save 用工单位签署合同记录
        //     const tenantRecordData = await tenantSignRecordService.create({
        //       contractId: tempFlowid,
        //       tenantId,
        //       tenantStatus: 'INIT',
        //       userId: userInfo.userId,
        //       startTime: startDate || '',
        //       endTime: endDate || '',
        //       monthlyPay: monthlyPay ? Number(monthlyPay) : 0,
        //     });
        //     console.log('tenantRecordData====', tenantRecordData);

        //     // 用工单位状态更新
        //     await tenantService.update({
        //       id: tenantId,
        //       latestFlowStatus: 'INIT',
        //       flowIds: tempFlowid,
        //       contractEndDate: flowInfos.Deadline,
        //       templateId: flowInfos.templateId,
        //     });

        //     // save to contract
        //     const flowInfosRes = await cloudApiClient.DescribeFlowDetailInfo({
        //       Agent: agent,
        //       FlowIds: flowRes.FlowIds || [],
        //     });
        //     console.log(flowInfosRes, 'flowInfosRes===');
        //     // 存储
        //     const saveDatas = (flowInfosRes.FlowInfo || []).map(item => ({
        //       ...item,
        //       UserId,
        //       contractStartTime: startDate || '',
        //       contractEndTime: endDate || '',
        //       monthlyPay: monthlyPay ? Number(monthlyPay) : 0,
        //     }));
        //     console.log(saveDatas, 'saveData======');
        //     // contractService.create(saveData);
        //     await Promise.all([saveDatas.map(item => contractService.create(item))]);
        //     return res.json({ code: 20000, data: saveDatas });
        //   }
        // } catch (error) {
        //   console.log('error====', error);
        //   logger.error({
        //     action: 'tenant/createFlowsByTemplates',
        //     data: body,
        //     errMessage: error,
        //   });
        //   return res.json({
        //     code: 500,
        //     message: error.message,
        //     requestId: error.requestId,
        //   });
        // }

        if (flowRes?.FlowIds && flowRes?.FlowIds?.length > 0) {
        // save to contract
          const flowInfosRes = await cloudApiClient.DescribeFlowDetailInfo({
            Agent: agent,
            FlowIds: flowRes.FlowIds || [],
          });

          const startDate = flowInfos?.FormFields.find(f => f.ComponentName === 'starttime')?.ComponentValue;
          const endDate = flowInfos?.FormFields.find(f => f.ComponentName === 'endtime')?.ComponentValue;
          const monthlyPay = flowInfos?.FormFields.find(f => f.ComponentName === 'monthlypay')?.ComponentValue;
          // 存储
          const saveDatas = (flowInfosRes.FlowInfo || []).map(item => ({
            ...item,
            UserId,
            organizationId: userInfo.organizationId,
          }));
          saveDatas.map(async (item) => {
            await contractService.create(item);

            // save 用工单位签署合同记录
            await tenantSignRecordService.create({
              contractId: item.FlowId,
              tenantId,
              tenantStatus: 'INIT',
              userId: userInfo.userId,
              startTime: startDate ? new Date(startDate) : null,
              endTime: endDate ? new Date(endDate) : null,
              monthlyPay: monthlyPay ? Number(monthlyPay) : 0,
            });

            await tenantService.update(tenantId, {
              latestFlowStatus: 'INIT',
              flowIds: item.FlowId,
              contractEndDate: flowInfos.Deadline ? new Date(flowInfos.Deadline) : null,
              templateId: flowInfos.templateId,
            });
          });
          // await Promise.all([saveDatas.map(item => contractService.create(item))]);

          // // save 用工单位签署合同记录
          // const tenantRecordData = await tenantSignRecordService.create({
          //   contractId: tempFlowid,
          //   tenantId,
          //   tenantStatus: 'INIT',
          //   userId: userInfo.userId,
          // });
          // console.log('tenantRecordData====', tenantRecordData);

          // 用工单位状态更新
          // await tenantService.update(tenantId, {
          //   id: tenantId,
          //   latestFlowStatus: 'INIT',
          //   flowIds: tempFlowid,
          //   contractEndDate: flowInfos.Deadline ? new Date(flowInfos.Deadline) : null,
          //   templateId: flowInfos.templateId,
          // });


          // contractService.create(saveData);

          logger.info({
            action: '/tenant/createFlowsByTemplates',
            data: {
              save: saveDatas,
            },
          });

          return res.json({ code: 20000, data: saveDatas });
        }

        res.json({
          code: 500,
        });
      } catch (error) {
        console.log('error====', error);
        logger.error({
          action: 'tenant/createFlowsByTemplates',
          data: body,
          errMessage: error,
        });
        return res.json({
          code: 500,
          message: error.message,
          requestId: error.requestId,
        });
      }
    }
  });

  // 渠道版撤销签署流程
  app.post(`${process.env.VUE_APP_BASE_API}/tenant/channelCancelFlow`, async (req, res) => {
    const { userInfo, body } = req;
    const targetUser = userInfo;
    if (targetUser) {
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: targetUser.organizationOpenId,
          OpenId: targetUser.openId,
          ProxyAppId: targetUser?.proxyAppId,
        }),
        Version: '2021-05-26',
        FlowId: body.flowId,
      };
      cloudApiClient
        .ChannelCancelFlow(params)
        .then(
          async (data) => {
            // update 用工单位签署合同记录
            await tenantSignRecordService.update(body.tenantId, {
              tenantStatus: 'UNDISTURBED',
            });

            // 用工单位状态更新
            await tenantService.update(body.tenantId, {
              id: body.tenantId,
              latestFlowStatus: 'UNDISTURBED',
              contractEndDate: null,
            });

            res.json({
              code: 20000,
              data,
            });
          },
          (err) => {
            // console.log('err====', err);
            res.json(err);
          },
        )
        .catch((error) => {
          console.log('error====', error);
        });
    } else {
      res.json({
        code: 500,
      });
    }
  });

  // 用工单位人员派遣详情
  app.post(`${process.env.VUE_APP_BASE_API}/tenant/sendWorkerRecord`, async (req, res) => {
    const { userInfo, body } = req;
    const { tenantId, limit, offset } = body;
    const targetUser = userInfo;
    if (targetUser) {
      let workerSendFilters = [];
      // 查询派遣记录
      const sendRecord = await sendService.filter({ tenantId });
      if (sendRecord) {
        for (const send of sendRecord) {
          // 根据派遣记录查询工人记录
          const workerData = await workerService.find(send.workerId);
          if (workerData) {
            workerSendFilters.push({
              ...send,
              workerName: workerData.name,
              workerMobile: workerData.mobile,
              workerGender: workerData.gender,
              workerIdcardNo: workerData.idcardNo,
              workerStatus: workerData.status,
            });
          } else {
            workerSendFilters = [...sendRecord];
          }
        }
        if (sendRecord) {
          return res.json({
            code: 20000,
            data: { list: workerSendFilters.slice(offset, offset + limit), totalCount: workerSendFilters.length },
            message: '查询用工单位人员派遣信息成功',
          });
        }
      }
      return res.json({
        code: 500,
        message: '查询用工单位人员派遣信息失败',
      });
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });
};
